'use client'
import './globals.css'
import { ConfigProvider, Layout, Menu, Dropdown, Avatar, Breadcrumb, Tabs } from 'antd'
import {
  DashboardOutlined,
  UserOutlined,
  TeamOutlined,
  MenuOutlined,
  LogoutOutlined,
  CloseOutlined
} from '@ant-design/icons'
import { usePathname, useRouter } from 'next/navigation'
import { ReactNode, Dispatch, useMemo, useCallback, useState } from 'react'
import Link from 'next/link'
import React, { createContext, useContext, useReducer } from 'react'
import PagePreloader from './components/PagePreloader'

const { Header, Sider, Content } = Layout

const menuItems = [
  { key: '/', icon: <DashboardOutlined />, label: '仪表盘' },
  { key: '/users', icon: <UserOutlined />, label: '用户管理' },
  { key: '/departments', icon: <TeamOutlined />, label: '部门管理' },
  { key: '/menus', icon: <MenuOutlined />, label: '菜单管理' },
]

const userMenuItems = [
  {
    key: 'logout',
    icon: <LogoutOutlined />,
    label: <Link href="/login">退出登录</Link>
  }
]

// 路由与菜单映射，便于面包屑和页签显示
const routeMap: Record<string, string[]> = {
  '/': ['仪表盘'],
  '/users': ['用户管理'],
  '/departments': ['部门管理'],
  '/menus': ['菜单管理'],
}

type Tab = { key: string; label: string; path: string }
type TabsState = { tabs: Tab[]; activeKey: string }
type TabsAction =
  | { type: 'ADD_TAB'; tab: Tab }
  | { type: 'REMOVE_TAB'; key: string }
  | { type: 'SWITCH_TAB'; key: string }

// 历史页签全局状态
const TabsContext = createContext<{
  state: TabsState;
  dispatch: Dispatch<TabsAction>;
} | null>(null)

function tabsReducer(state: TabsState, action: TabsAction): TabsState {
  switch (action.type) {
    case 'ADD_TAB': {
      const exists = state.tabs.find(tab => tab.key === action.tab.key)
      if (exists) {
        return { ...state, activeKey: action.tab.key }
      }
      return {
        tabs: [...state.tabs, action.tab],
        activeKey: action.tab.key,
      }
    }
    case 'REMOVE_TAB': {
      const tabs = state.tabs.filter(tab => tab.key !== action.key)
      let activeKey = state.activeKey
      if (activeKey === action.key && tabs.length > 0) {
        activeKey = tabs[tabs.length - 1].key
      }
      return { tabs, activeKey }
    }
    case 'SWITCH_TAB':
      return { ...state, activeKey: action.key }
    default:
      return state
  }
}

function TabsProvider({ children }: { children: ReactNode }) {
  const [state, dispatch] = useReducer(tabsReducer, {
    tabs: [
      { key: '/', label: '仪表盘', path: '/' }
    ],
    activeKey: '/',
  })
  return (
    <TabsContext.Provider value={{ state, dispatch }}>
      {children}
    </TabsContext.Provider>
  )
}

export function useTabs() {
  const ctx = useContext(TabsContext)
  if (!ctx) throw new Error('useTabs must be used within TabsProvider')
  return ctx
}

// 面包屑组件 - 使用 useMemo 优化
function BreadcrumbNav({ pathname }: { pathname: string }) {
  const items = useMemo(() => {
    const paths = pathname === '/' ? ['/'] : pathname.split('/').filter(Boolean).map((_, idx, arr) => '/' + arr.slice(0, idx + 1).join('/'))
    return paths.map((p, i) => ({
      title: routeMap[p]?.[0] || p,
      key: p,
    }))
  }, [pathname])
  
  return <Breadcrumb items={items} style={{ fontSize: 14 }} />
}

// 历史页签组件 - 优化性能
function HistoryTabs() {
  const { state, dispatch } = useTabs()
  const router = useRouter()
  const pathname = usePathname()

  // 自动添加当前路由到历史页签
  React.useEffect(() => {
    const label = routeMap[pathname]?.[0] || pathname
    dispatch({ type: 'ADD_TAB', tab: { key: pathname, label, path: pathname } })
  }, [pathname, dispatch])

  const handleTabChange = useCallback((key: string) => {
    if (key !== pathname) router.push(key)
  }, [pathname, router])

  const handleTabEdit = useCallback((targetKey: React.Key | string | React.MouseEvent<Element> | React.KeyboardEvent<Element>, action: 'add' | 'remove') => {
    if (action === 'remove') {
      const key = typeof targetKey === 'string' ? targetKey : (targetKey as any).key || targetKey
      const isCurrentTab = key === pathname
      dispatch({ type: 'REMOVE_TAB', key: key as string })
      if (isCurrentTab) {
        setTimeout(() => {
          const remainingTabs = state.tabs.filter(tab => tab.key !== key)
          if (remainingTabs.length > 0) {
            const lastTab = remainingTabs[remainingTabs.length - 1]
            router.push(lastTab.key)
          }
        }, 0)
      }
    }
  }, [pathname, state.tabs, router, dispatch])

  const tabItems = useMemo(() => 
    state.tabs.map(tab => ({
      label: tab.label,
      key: tab.key,
      closable: tab.key !== '/',
    })), [state.tabs]
  )

  return (
    <Tabs
      type="editable-card"
      hideAdd
      size="small"
      tabBarStyle={{ margin: 0, padding: 0 }}
      moreIcon={null}
      activeKey={pathname}
      onChange={handleTabChange}
      onEdit={handleTabEdit}
      items={tabItems}
    />
  )
}

export default function RootLayout({ children }: { children: ReactNode }) {
  const pathname = usePathname()
  const router = useRouter()
  
  // 优化菜单点击处理 - 移除加载状态以避免闪烁
  const handleMenuClick = useCallback(({ key }: { key: string }) => {
    if (key !== pathname) {
      // 预加载目标页面
      router.prefetch(key as string)
      router.push(key as string)
    }
  }, [pathname, router])

  return (
    <html lang="zh-CN">
      <head>
        <style>{`
          html, body, #__next {
            overflow: hidden !important;
            height: 100% !important;
          }
          .ant-layout, .ant-layout-content {
            height: 100% !important;
            min-height: 0 !important;
          }
          .ant-tabs-tab {
            border-radius: 0 !important;
            margin: 0 !important;
            background: #fff !important;
            border: none !important;
            border-right: 1px solid #f0f0f0 !important;
            padding: 0 8px !important;
            min-width: 0 !important;
            height: 32px !important;
            line-height: 32px !important;
          }
          .ant-tabs-tab:last-child {
            border-right: none !important;
          }
          .ant-tabs-tab-active {
            color: #1677ff !important;
          }
          .ant-tabs-content-holder,
          .ant-tabs-content {
            margin: 0 !important;
            padding: 0 !important;
            border: none !important;
            background: #fff !important;
          }
          .ant-tabs-top {
            margin-bottom: 0 !important;
            padding-bottom: 0 !important;
            border-bottom: none !important;
          }
          .ant-tabs-nav {
            border-bottom: none !important;
          }
          .ant-tabs-nav::before {
            border-bottom: none !important;
          }
          .ant-tabs-nav-list {
            position: relative !important;
          }
          /* 优化表格内部滚动条样式 */
          .ant-table-body {
            scrollbar-width: thin;
            scrollbar-color: #bfbfbf #f5f5f5;
          }
          .ant-table-body::-webkit-scrollbar {
            width: 8px;
            background: #f5f5f5;
            border-radius: 4px;
          }
          .ant-table-body::-webkit-scrollbar-thumb {
            background: #bfbfbf;
            border-radius: 4px;
          }
          .ant-table-body::-webkit-scrollbar-thumb:hover {
            background: #a0a0a0;
          }
          /* 移除页面切换动画，避免闪烁 */
          .page-content {
            background: #f5f5f5;
            min-height: 100%;
            padding: 16px;
            transition: none !important;
          }
          /* 确保内容区域平滑过渡 */
          .ant-layout-content {
            transition: none !important;
          }
          /* 优化菜单项点击效果 */
          .ant-menu-item {
            transition: all 0.2s ease !important;
          }
          .ant-menu-item:hover {
            background-color: rgba(255, 255, 255, 0.1) !important;
          }
          .ant-menu-item-selected {
            background-color: #1677ff !important;
          }
        `}</style>
      </head>
      <body style={{ height: '100%' }}>
        <ConfigProvider
          theme={{
            token: {
              colorPrimary: '#1677ff',
            },
          }}
        >
          <TabsProvider>
            <Layout style={{ minHeight: '100vh' }}>
              <Sider collapsible style={{ position: 'fixed', height: '100vh', left: 0, top: 0, zIndex: 1000 }}>
                <div style={{ height: 48, margin: 16, background: 'rgba(255,255,255,0.2)', color: '#fff', fontWeight: 700, fontSize: 20, textAlign: 'center', lineHeight: '48px' }}>
                  简单管理平台
                </div>
                <Menu
                  theme="dark"
                  mode="inline"
                  selectedKeys={[pathname]}
                  items={menuItems}
                  onClick={handleMenuClick}
                  style={{ borderRight: 'none' }}
                />
              </Sider>
              <Layout style={{ marginLeft: 200 }}>
                <Header style={{ background: '#fff', padding: '0 24px', display: 'flex', flexDirection: 'row', alignItems: 'center', position: 'fixed', top: 0, right: 0, left: 200, zIndex: 999, height: 48, boxShadow: 'none', borderBottom: '1px solid #f0f0f0' }}>
                  <BreadcrumbNav pathname={pathname} />
                  <Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
                    <span style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', marginLeft: 'auto' }}>
                      <Avatar style={{ backgroundColor: '#1677ff', marginRight: 8 }} icon={<UserOutlined />} />
                      admin
                    </span>
                  </Dropdown>
                </Header>
                {/* 历史页签紧贴Header底部 */}
                <div style={{ position: 'fixed', left: 200, right: 0, top: 48, zIndex: 998, background: '#fff' }}>
                  <div style={{ height: 32, display: 'flex', alignItems: 'center', background: 'transparent', padding: '0 24px', margin: 0 }}>
                    <div style={{ flex: 1 }}>
                      <HistoryTabs />
                    </div>
                  </div>
                </div>
                <Content style={{ background: '#fff', marginTop: 80, marginLeft: 0, borderRadius: 0, boxShadow: 'none', padding: 0, border: 'none' }}>
                  <div className="page-content">
                    {children}
                  </div>
                </Content>
                <PagePreloader />
              </Layout>
            </Layout>
          </TabsProvider>
        </ConfigProvider>
      </body>
    </html>
  )
}
